#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
from: http://code.activestate.com/recipes/189060-using-berkeley-db-database/
'''

__author__ = 'lyj'


from bsddb3 import db


dbenv = None

def event_callback(event, data, etc):
    print 'Event:', event
    print data
    print etc

def open_dbenv(homedir="."):
    global dbenv
    flags = db.DB_CREATE | db.DB_INIT_LOG | db.DB_INIT_TXN | \
            db.DB_RECOVER | db.DB_INIT_LOCK | db.DB_INIT_MPOOL | \
            db.DB_THREAD | db.DB_INIT_REP
    
    dbenv = db.DBEnv()
    dbenv.set_event_notify(event_callback)
    #dbenv.rep_set_limit(0, db.REPLIMIT)
    dbenv.set_flags(db.DB_AUTO_COMMIT | db.DB_TXN_NOSYNC, 1)
    dbenv.set_lk_detect(db.DB_LOCK_DEFAULT)
    #dbenv.repmgr_set_local_site(listen_host, port, 0)
    #dbenv.rep_set_priority(100)
    dbenv.repmgr_set_ack_policy(db.DB_REPMGR_ACKS_ONE)
    
    dbenv.open(homedir, flags)
    #dbenv.repmgr_start(3, db.DB_REP_ELECTION)

def close_dbenv():
    if dbenv:
        dbenv.txn_checkpoint()
        dbenv.close()

# Part 1:
#
homedir = r'j:\_DevTemp'
filename = r'j:\_DevTemp\fruit'

open_dbenv(homedir)
fruitDB = db.DB(dbenv)
# open(filename, dbname=None, dbtype=DB_UNKNOWN, flags=0, mode=0660, txn=None)
# filename => 生成的 数据库文件名
# dbname => 可选，数据库名
# dbtype => DB_BTREE, DB_HASH, DB_HEAP, DB_QUEUE, DB_RECNO, or DB_UNKNOWN其中一个
# flags => 多进程时:DB_INIT_MPOOL and DB_INIT_LOCK were required. Also important is the need to pass dbenv to db_create().
# 参考: http://www.lotterer.net/blog/en/60-multiple-writer-processes-with-berkeley-db
# mode => 权限，Linux专用
dbname = None
dbtype = db.DB_HASH
flags = db.DB_CREATE
fruitDB.open(filename, dbname, dbtype, flags)
try:
    fruitDB.put("apple","red")
    fruitDB.put("orange","orange")
    fruitDB.put("banana","yellow")
    fruitDB.put("tomato","red")
finally:
    fruitDB.close()
    if dbenv:
        close_dbenv()


if __name__ == '__main__':
    pass  